package com.project.forpersonaluse;

import static android.icu.math.BigDecimal.ROUND_HALF_UP;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;

import java.math.BigDecimal;

import com.project.forpersonaluse.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    /**
     * 保留小数
     */
    private final int KEEP_DECIMALS = 4;
    /**
     * 输入数量的值
     */
    private String mNumber = "0";
    /**
     * 输入单价的值
     */
    private String mPrice = "0";
    /**
     * 费用
     */
    private String mCost = "0";
    /**
     * 汇率
     */
    private String mExchangeRate = "0";
    /**
     * 海运费
     */
    private String mOceanFreight = "0";
    /**
     * 港杂费
     */
    private String mPortCharges = "0";
    /**
     * 退税率
     */
    private String mTaxRate = "0.13";
    /**
     * 采购总价/柜
     */
    private String mTotalPrice = "";
    /**
     * 采购总价/柜et
     */
    private String mAmount = "";
    /**
     * 经支
     */
    private String mJingZhi = "0";
    /**
     * 纬支
     */
    private String mWeiZhi = "0";
    /**
     * 系数
     */
    private String mCoefficient = "65";
    /**
     * 经密
     */
    private String mJingMi = "0";
    /**
     * 纬密
     */
    private String mWeiMi = "0";
    /**
     * 幅宽
     */
    private String mWidthCloth = "0";
    /**
     * 经纱
     */
    private String mJingSha = "0";
    /**
     * 纬纱
     */
    private String mWeiSha = "0";
    /**
     * 加工费
     */
    private String mProcessingFee = "0";
    /**
     * 柜重
     */
    private String mGuizhong = "25.8";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        super.onCreate(savedInstanceState);
        binding.etPrice.setFilters(new InputFilter[]{lendFilter});
        //监听输入数量
        binding.etNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 文本变化前的处理
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 文本变化时的处理
            }

            @Override
            public void afterTextChanged(Editable s) {
                mNumber = s.toString().trim();
                countTotalPrice();
                countUnitPrice();
            }
        });
        //监听单价
        binding.etPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    // 在原来基础上加0.10
                    BigDecimal num1 = new BigDecimal(s.toString().trim());
                    BigDecimal num2 = new BigDecimal("0.10");
                    mPrice = num1.add(num2).toString();
                    countTotalPrice();
                } catch (Exception e) {

                }
            }
        });
        //监听费用
        binding.etCost.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mCost = s.toString().trim();
                countAmount();
            }
        });
        //监听汇率
        binding.etExchangeRate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mExchangeRate = s.toString().trim();
                countExchangeRate();
            }
        });
        //退税率
        binding.etTaxRate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String value = s.toString().trim();
                BigDecimal b1 = new BigDecimal(value);
                BigDecimal b2 = new BigDecimal("100");
                BigDecimal b3 = b1.divide(b2, KEEP_DECIMALS, BigDecimal.ROUND_HALF_UP);
                mTaxRate = b3.toString();
                countExchangeRate();
            }
        });
        //监听海运费
        binding.etOceanFreight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mOceanFreight = s.toString().trim();
                countTotalPayment();
            }
        });
        //监听港杂费
        binding.etPortCharges.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mPortCharges = s.toString().trim();
                countTotalPayment();
            }
        });

        //点击清空
        binding.btnClear.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, MainActivity.class));
            finish();
        });
        //点击计算
        binding.btnCount.setOnClickListener(v -> {
            try {
                countTotalPrice();
                countAmount();
                countExchangeRate();
                countDollar();
                countTotalPayment();
                countUnitPrice();
            } catch (Exception e) {
            }
        });
        //经支
        binding.etJingZhi.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mJingZhi = s.toString().trim();
                CalculatePrice();
            }
        });
        //纬支
        binding.etWeiZhi.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mWeiZhi = s.toString().trim();
                CalculatePrice();
            }
        });
        //系数
        binding.etCoefficient.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mCoefficient = s.toString().trim();
                CalculatePrice();
            }
        });
        //经密
        binding.etJingMi.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mJingMi = s.toString().trim();
                CalculatePrice();
            }
        });
        //纬密
        binding.etWeiMi.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mWeiMi = s.toString().trim();
                CalculatePrice();
            }
        });
        //幅宽
        binding.etWidthCloth.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mWidthCloth = s.toString().trim();
                CalculatePrice();
            }
        });
        //经纱
        binding.etJingSha.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mJingSha = s.toString().trim();
                CalculatePrice();
            }
        });
        //纬纱
        binding.etWeiSha.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mWeiSha = s.toString().trim();
                CalculatePrice();
            }
        });
        //加工费
        binding.etProcessingFee.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mProcessingFee = s.toString().trim();
                CalculatePrice();
            }
        });
        //柜重
        binding.etGuizhong.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mGuizhong = s.toString().trim();
                CalculatePrice();
            }
        });
    }

    /**
     * 设置小数后位数控制
     */
    private InputFilter lendFilter = (source, start, end, dest, dstart, dend) -> {
        // 删除等特殊字符，直接返回
        if ("".equals(source.toString())) {
            return null;
        }
        String dValue = dest.toString();
        String[] splitArray = dValue.split("\\.");
        if (splitArray.length > 1) {
            String dotValue = splitArray[1];
            int diff = dotValue.length() + 1 - 4;//4表示输入框的小数位数
            if (diff > 0) {
                return source.subSequence(start, end - diff);
            }
        }
        return null;
    };

    /**
     * 计算合计柜款
     */
    private void countTotalPayment() {
        try {
            String mDollar = binding.etDollar.getText().toString();
            //如果为空，就不计算，且把合计柜款设为0.00
            if (TextUtils.isEmpty(mDollar) || TextUtils.isEmpty(mOceanFreight) || TextUtils.isEmpty(mPortCharges)) {
                binding.etTotalPayment.setText("0.00");
                return;
            }
            //美金
            BigDecimal bDollar = new BigDecimal(mDollar);
            //海运费
            BigDecimal bOceanFreight = new BigDecimal(mOceanFreight);
            //港杂费
            BigDecimal bPortCharges = new BigDecimal(mPortCharges);
            //保留4位小数，四舍五入
            BigDecimal value = bDollar.add(bOceanFreight).add(bPortCharges);
            binding.etTotalPayment.setText(value.toString());
            countUnitPrice();
        } catch (Exception e) {
        }
    }

    /**
     * 计算单价
     */
    private void countUnitPrice() {
        String mUnitPrice = binding.etTotalPayment.getText().toString();
        if (!TextUtils.isEmpty(mNumber) && !TextUtils.isEmpty(mUnitPrice)) {
            //数量
            BigDecimal bNumber = new BigDecimal(mNumber);
            //计算合计柜款
            BigDecimal bUnitPrice = new BigDecimal(mUnitPrice);
            BigDecimal bigDecimal = bUnitPrice.divide(bNumber, KEEP_DECIMALS, BigDecimal.ROUND_HALF_UP);
            binding.etUnitPrice.setText(bigDecimal.toString());
        }
    }

    /**
     * 计算汇率
     */
    private void countExchangeRate() {
        try {
            //如果汇率为空，就不计算，且把换汇率设为0.00
            if (TextUtils.isEmpty(mExchangeRate) || TextUtils.isEmpty(mTaxRate)) {
                binding.etSwapRate.setText("0.00");
                return;
            }
            //汇率/(1-(1/1.13*mTaxRate))
            BigDecimal b1 = new BigDecimal("1.13");
            BigDecimal b2 = new BigDecimal(mTaxRate);
            BigDecimal b3 = new BigDecimal("1");
            BigDecimal b4 = b3.divide(b1, KEEP_DECIMALS, BigDecimal.ROUND_HALF_UP);
            BigDecimal b5 = b2.multiply(b4);
            BigDecimal b6 = b3.subtract(b5);
            BigDecimal b7 = new BigDecimal(mExchangeRate);
            //保留4位小数，四舍五入
            BigDecimal value = b7.divide(b6, KEEP_DECIMALS, BigDecimal.ROUND_HALF_UP);
            binding.etSwapRate.setText(value.toString());
            countDollar();
        } catch (Exception e) {
        }
    }

    /**
     * 计算折美金
     */
    private void countDollar() {
        //换汇率
        String mSwapRate = binding.etSwapRate.getText().toString();
        //如果合计和换汇率为空，就不计算，且把折美元设为0.00
        if (TextUtils.isEmpty(mAmount) || TextUtils.isEmpty(mSwapRate)) {
            binding.etDollar.setText("0.00");
            return;
        }
        //合计
        BigDecimal bAmount = new BigDecimal(mAmount);
        //换汇率
        BigDecimal bSwapRate = new BigDecimal(mSwapRate);
        BigDecimal value = bAmount.divide(bSwapRate, KEEP_DECIMALS, BigDecimal.ROUND_HALF_UP);
        binding.etDollar.setText(value.toString());
    }

    /**
     * 计算采购总价的值
     */
    private void countTotalPrice() {
        try {
            //如果数量或者价格为空，就不计算，且把采购总价设为0.00
            if (TextUtils.isEmpty(mNumber) || TextUtils.isEmpty(mPrice)) {
                binding.etTotalPrice.setText("0.00");
                return;
            }
            //数量
            BigDecimal bNumber = new BigDecimal(mNumber);
            //单价
            BigDecimal bPrice = new BigDecimal(binding.etPrice.getText().toString().trim());
            //保留4位小数，四舍五入
            BigDecimal value = bNumber.multiply(bPrice).setScale(KEEP_DECIMALS, ROUND_HALF_UP);
            binding.etTotalPrice.setText(value.toString());
            //单价
            BigDecimal bPrice2 = new BigDecimal(mPrice);
            //保留4位小数，四舍五入
            BigDecimal value2 = bNumber.multiply(bPrice2).setScale(KEEP_DECIMALS, ROUND_HALF_UP);
            mTotalPrice = value2.toString();
            countAmount();
        } catch (Exception e) {
        }
    }

    /**
     * 计算合计的值
     */
    private void countAmount() {
        try {
            //如果采购总价或者费用为空，就不计算，且把采购总价设为0.00
            if (TextUtils.isEmpty(mTotalPrice) || TextUtils.isEmpty(mCost)) {
                binding.etAmount.setText("0.00");
                return;
            }
            //数量
            BigDecimal bTotalPrice = new BigDecimal(binding.etTotalPrice.getText().toString().trim());
            //单价
            BigDecimal bCost = new BigDecimal(mCost);
            //保留4位小数，四舍五入
            BigDecimal value = bTotalPrice.add(bCost).setScale(KEEP_DECIMALS, ROUND_HALF_UP);
            binding.etAmount.setText(value.toString());
            //数量
            BigDecimal bTotalPrice2 = new BigDecimal(mTotalPrice);
            //保留4位小数，四舍五入
            BigDecimal value2 = bTotalPrice2.add(bCost).setScale(KEEP_DECIMALS, ROUND_HALF_UP);
            mAmount = value2.toString();
            countDollar();
        } catch (Exception e) {
        }
    }

    /**
     * 计算单价
     */
    private void CalculatePrice() {
        try {
            if (TextUtils.isEmpty(mJingZhi) || TextUtils.isEmpty(mWeiZhi) || TextUtils.isEmpty(mJingMi) || TextUtils.isEmpty(mWeiMi)
                    || TextUtils.isEmpty(mWidthCloth) || TextUtils.isEmpty(mJingSha) || TextUtils.isEmpty(mWeiSha)
                    || TextUtils.isEmpty(mProcessingFee) || TextUtils.isEmpty(mCoefficient) || TextUtils.isEmpty(mGuizhong)) {

            } else {
                //经支
                BigDecimal bdA = new BigDecimal(mJingZhi);
                //纬支
                BigDecimal bdB = new BigDecimal(mWeiZhi);
                //经密
                BigDecimal bdC = new BigDecimal(mJingMi);
                //纬密
                BigDecimal bdD = new BigDecimal(mWeiMi);
                //幅宽
                BigDecimal bdE = new BigDecimal(mWidthCloth);
                //经纱
                BigDecimal bdF = new BigDecimal(mJingSha);
                //纬纱
                BigDecimal bdG = new BigDecimal(mWeiSha);
                //加工费
                BigDecimal bdH = new BigDecimal(mProcessingFee);
                //系数
                BigDecimal bdCoefficient = new BigDecimal(mCoefficient);
                //柜重
                BigDecimal bdGuizhong = new BigDecimal(mGuizhong);
                //系数值
                BigDecimal num7 = bdCoefficient.divide(new BigDecimal("100000"));
                //数值1：经密/经支*幅宽*经纱*（系数/）
                BigDecimal num1 = bdC.divide(bdA, KEEP_DECIMALS, BigDecimal.ROUND_HALF_UP).multiply(bdE).multiply(bdF).multiply(num7);
                //数值2：纬密/纬支*幅宽*纬纱*（0.000+系数）
                BigDecimal num2 = bdD.divide(bdB, KEEP_DECIMALS, BigDecimal.ROUND_HALF_UP).multiply(bdE).multiply(bdG).multiply(num7);
                //数值3：加工费*纬密
                BigDecimal num3 = bdH.multiply(bdD);
                //单价：数值1+数值2+数值3
                BigDecimal bgResult = num1.add(num2).add(num3).setScale(KEEP_DECIMALS, ROUND_HALF_UP);
                binding.etUnivalent.setText(bgResult.toString());
                /**
                 * 平方米克重 =（经密+纬密）÷（（经支+纬支）÷2）×1.1×0.588x39.37
                 */
                //数值4：经密+纬密
                BigDecimal num4 = bdC.add(bdD);
                //数值5：（（经支+纬支）÷2）
                BigDecimal num5 = (bdA.add(bdB)).divide(new BigDecimal("2"), KEEP_DECIMALS, BigDecimal.ROUND_HALF_UP);
                //数值6：数值4÷数值5×25.464516
                BigDecimal num6 = num4.divide(num5, KEEP_DECIMALS, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("25.464516")).setScale(KEEP_DECIMALS, ROUND_HALF_UP);
                binding.etWeight.setText(num6.toString());
                //G/M = GSM x 幅宽×2.54/100
                BigDecimal num8 = bdE.multiply(num6).multiply(new BigDecimal("2.54")).divide(new BigDecimal("100"), KEEP_DECIMALS, BigDecimal.ROUND_HALF_UP).setScale(KEEP_DECIMALS, ROUND_HALF_UP);
                binding.etGm.setText(num8.toString());
                //米数 = 25.8X1000 / 350X1000=73714.29
                BigDecimal num9 = bdGuizhong.multiply(new BigDecimal("1000")).multiply(new BigDecimal("1000")).divide(num8, KEEP_DECIMALS, BigDecimal.ROUND_HALF_UP).setScale(KEEP_DECIMALS, ROUND_HALF_UP);
                binding.etMishu.setText(num9.toString());
            }
        } catch (Exception e) {
            Log.e("info", e.toString());
        }
    }

}